package com.liyiyan.note.util;

import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.liyiyan.note.R;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

public class GetHtmlService extends Thread {
	//called Service, but not really an android service.
	public static String TAG = "GetHtmlService";
	public static String HOST_HOME = "http://note.liyiyan.com/";
	public static String TEST_HOME = "http://192.168.0.109/note/";
	
	String LOCAL_HOME = HOST_HOME; 
	
	public static String INSERT = "insert.php";
	public static String DISPLAY = "display.php";
	public static String DELETE = "delete.php";
	public static String UPDATE = "update.php";
	
	private static HttpClient httpClient = initHttpClient();

	private String type = ""; 
	private Handler handler;
	List<NameValuePair> params;
	private ProgressDialog progressDialog;
	
	public static HttpClient getHttpClient(){
		if (httpClient != null){
			httpClient = initHttpClient();
		}
		return httpClient;
	}

	public GetHtmlService(Context context, Handler handler, String type,
			List<NameValuePair> params) {
		this.handler = handler;
		this.params = params;
		this.type = type;
		
		String title = context.getResources().getString(R.string.waitTitle);
		String content = context.getResources().getString(R.string.waitContent);
		progressDialog = ProgressDialog.show(context, title, content,
				true);

	}

	public String postData(String url, List<NameValuePair> nameValuePairs)
			throws IllegalStateException, Exception {
		// Create a new HttpClient and Post Header
		progressDialog.show();
		HttpPost httppost = new HttpPost(url);
		HttpClient httpclient = getHttpClient();
		HttpEntity entity = null;
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "ISO-8859-1"));
			//This is default encoding for many servers.
			
			// Execute HTTP Post Request
			
			HttpResponse response = httpclient.execute(httppost);
			Header[] headers = response.getAllHeaders();
			for (int i = 0; i < headers.length; i++) {
				Log.i("header"+i, headers[i].getName());
				Log.i("value"+i, headers[i].getValue());
			}
			entity = response.getEntity();
			try {
				progressDialog.dismiss();
			} catch (Exception e) {
				Log.i("GetHtmlService", e.getMessage());
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			progressDialog.dismiss();
		} catch (IOException e) {
			e.printStackTrace();
			progressDialog.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
			progressDialog.dismiss();
		}

		if (entity != null) {
			String result =  new String(HelperTool.readInputStream(entity.getContent()),
					"UTF-8");
			Log.i(TAG, result);
			if (result.contains("<html>")){
				
				HttpResponse response = httpclient.execute(httppost);
				entity = response.getEntity();
				result =  new String(HelperTool.readInputStream(entity.getContent()),
						"UTF-8");
			}
			return result;
			
		} else {
			return "";
		}

	}

	public void run() {
		String result = null;
		Looper.prepare();
		while (result == null) {
			try {
				/**
				 * String type = params.get(0).getValue(); if
				 * (type.compareTo("browse_tea")==0||type.compareTo("tea")==0){
				 * result = postData(HOST_HOME, params); } else { result =
				 * postData(HOST, params); } //
				 **/
				
				String urlString = "";
				if (type == INSERT){
					urlString = LOCAL_HOME + INSERT;
				} else if (type == DISPLAY) {
					urlString = LOCAL_HOME + DISPLAY;
				} else if (type == DELETE) {
					urlString = LOCAL_HOME + DELETE;
				} else {
					urlString = LOCAL_HOME + type;
					//throw new Exception("unknow type: " + type);
				}
				result = postData(urlString, params);
			} catch (IllegalStateException e) {
				e.printStackTrace();
				progressDialog.dismiss();
			} catch (Exception e) {
				e.printStackTrace();
				progressDialog.dismiss();
			}
		}
		if (handler != null) {
			Message msg = handler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("result", result);
			msg.setData(b);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		if (this.progressDialog!= null){
			progressDialog.dismiss();
		}
		super.destroy();
	}

	@Override
	public State getState() {
		// TODO Auto-generated method stub
		return super.getState();
	}
	
	
	private static HttpClient initHttpClient(){

		int connection_Timeout = 7000; // = 7 sec
		
		HttpParams my_httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(my_httpParams,
				connection_Timeout);
		HttpConnectionParams.setSoTimeout(my_httpParams, connection_Timeout);
		HttpClient httpclient = new DefaultHttpClient(my_httpParams);
		return httpclient;
	}
	
}